package com.hpf.tool.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * 
 * @author hpf
 *
 */
public final class HttpClientUtils {
	private static void close(CloseableHttpClient client) {
		if (client != null) {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * POST 请求
	 * @param url
	 * @param param
	 * @return
	 */
	public static String postRequest(String url, Map<String, String> params) {
		CloseableHttpClient client = HttpClients.createDefault();
		try {
			HttpPost post = new HttpPost(url);
			if (params != null && params.isEmpty() == false) {
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> item : params.entrySet()) {
					nvps.add(new BasicNameValuePair(item.getKey(), item.getValue()));
				}
				post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			}
			CloseableHttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity == null) {
				throw new RuntimeException("返回结果为空");
			}
			return EntityUtils.toString(entity);
		} catch(Exception ex){
			throw new RuntimeException(ex);
		} finally {
			close(client);
		}
	}

	public static void main(String[] args) {
		String url = "http://erp.111.com.cn/sd/recipeOrder/showList.action";
		String result = HttpClientUtils.postRequest(url,null);
		
		System.out.println(result);
	}
}